package com.llw.notify.mail_sender;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.llw.notify.databinding.ActivityManageEmailBinding;
import com.llw.notify.setting.SettingsManager;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

public class ManageEmailActivity extends AppCompatActivity {
    private final String TAG = getClass().getSimpleName();

    private ActivityManageEmailBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityManageEmailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setTitle("邮箱管理");

        initButtonListener();
        initEditText();
    }

    private void initButtonListener() {
        binding.resetSender.setOnClickListener((view) -> {
            binding.senderAddressEditText.setText(SettingsManager.getSenderEmail());
            binding.passportEditText.setText(SettingsManager.getSenderEmailPassport());
        });
        binding.saveSender.setOnClickListener((view) -> {
            final String senderAddress = binding.senderAddressEditText.getText().toString().trim();
            final String passport = binding.passportEditText.getText().toString().trim();
            if (validSenderEmail(senderAddress, passport) == false) {
                return;
            }
            SettingsManager.setSender(senderAddress, passport);
            shortToast("保存发送方信息成功");
        });

        binding.resetReceiver.setOnClickListener((view) -> {
            binding.receiverAddressEditText.setText(SettingsManager.getReceiverEmail());
        });
        binding.saveReceiver.setOnClickListener((view) -> {
            final String receiverAddress = binding.receiverAddressEditText.getText().toString().trim();
            if (receiverAddress.isEmpty()) {
                shortToast("请输入接收方邮箱地址");
                return;
            }
            SettingsManager.setReceiver(receiverAddress);
            shortToast("保存接收方地址成功");
        });

        binding.testEmail.setOnClickListener((view) -> {
            testEmail();
        });
    }

    private boolean isEmpty(final String... strings) {
        for (String string : strings) {
            if (string.isEmpty()) {
                return true;
            }
        }
        return false;
    }

    private boolean validSenderEmail(final String senderAddress, final String passport) {
        if (isEmpty(senderAddress, passport)) {
            shortToast("请先完善发送方信息");
            return false;
        }
        if (EmailServer.getEmailServerType(senderAddress) == EmailServer.ServiceProvider.Unknown) {
            shortToast("仅支持163、126、qq邮箱\n不支持该类型的发送方邮箱");
            return false;
        }
        return true;
    }

    private void initEditText() {
        binding.senderAddressEditText.setText(SettingsManager.getSenderEmail());
        binding.passportEditText.setText(SettingsManager.getSenderEmailPassport());
        binding.receiverAddressEditText.setText(SettingsManager.getReceiverEmail());
    }

    private void testEmail() {
        final String senderAddress = binding.senderAddressEditText.getText().toString().trim();
        final String passport = binding.passportEditText.getText().toString().trim();
        if (validSenderEmail(senderAddress, passport) == false) {
            return;
        }

        final String receiverAddress = binding.receiverAddressEditText.getText().toString().trim();
        if (receiverAddress.isEmpty()) {
            shortToast("请输入接收方邮箱地址");
            return;
        }

        final String senderHost = EmailServer.getEmailHost(senderAddress);
        final String senderPort = EmailServer.getEmailServerPort(senderAddress);
        new Thread(() -> {
            try {
                EmailSender emailSender = new EmailSender();
                emailSender.setProperties(senderHost, senderPort);
                emailSender.setMessage(senderAddress, "邮箱可用性测试", "邮箱可用性测试");
                emailSender.setReceiver(new String[]{receiverAddress});
                emailSender.sendEmail(senderHost, senderAddress, passport);
                Log.i(TAG, "发送测试邮件成功");
                shortToast("发送测试邮件成功\n请手动检查是否收到了测试邮件");
            } catch (AddressException e) {
                shortToast("接收或发送邮箱地址错误，请检查");
                e.printStackTrace();
            } catch (MessagingException e) {
                shortToast("请检查：\n1. 网络是否已连接\n2. 邮箱的SMTP服务器地址是否改变");
                e.printStackTrace();
            }
        }).start();
    }

    private void shortToast(String message) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(ManageEmailActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        });
    }
}